package com.lagou.demo03.dao;

import com.lagou.demo03.model.Class;
import com.lagou.demo03.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class ClassQueryDaoImp implements ClassQueryDao {
    @Override
    public List<Class> classQuery() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<Class> classList = new LinkedList<>();

        try {
            //获取数据库连接
            connection = DbUtil.getConnection();
            //从数据库中获取数据
            String sql2 = "SELECT * FROM t_class";
            //执行sql，并获取结果返回
            preparedStatement = connection.prepareStatement(sql2);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Class cls = new Class(resultSet.getString("className"),resultSet.getString("grade"),resultSet.getString("teacher"),
                        resultSet.getString("slogan"),resultSet.getInt("classNumber"));
                classList.add(cls);
            }
            return classList;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                DbUtil.closeResource(connection,preparedStatement);
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
